let express = require('express')
let fs = require('fs')
let path = require('path')
let jwt = require('jsonwebtoken')

let userRouter = express.Router()

// 注册功能
userRouter.post('/register', (req, res) => {
    let { phone } = req.body

    // 读取users.json文件中的用户数据
    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    // 判断新用户是否存在
    let i = arr.findIndex((item) => {
        return item.phone == phone
    })
    if (i == -1) {
        arr.push({ ...req.body, group: '开发组', isadmin: true, status: true })
        // 写入数据
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8')
        res.send({ code: 200, msg: '注册成功' })
    } else {
        res.send({ code: 400, msg: '该手机号已被注册，注册失败' })
    }
})

// 登陆功能
userRouter.post('/login', (req, res) => {
    let { phone, pass } = req.body

    // 读取users.json文件中的用户数据
    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    // 判断arr中是否有这个用户信息
    let i = arr.findIndex((item) => {
        return item.phone == phone && item.pass == pass
    })
    if (i != -1) {
        let token = jwt.sign({ phone }, '1234', { algorithm: 'HS256', expiresIn: 60 })
        res.send({ code: 200, msg: '登陆成功', userinfo: arr[i],token })
    } else {
        res.send({ code: 400, msg: '登陆失败' })
    }
})
// 分页功能
userRouter.get('/list', (req, res) => {
    let { page, count } = req.query

    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let newarr = arr.slice((page - 1) * count, page * count)
    // 总页数
    let total = Math.ceil(arr.length / count)
    res.send({ code: 200, msg: '渲染完成', list: newarr, total: total })
})
// 搜索功能
userRouter.get('/search', (req, res) => {
    let { searchkey, page, count } = req.query

    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let newarr = arr.filter((item) => {
        return item.name.includes(searchkey)
    })
    let searcharr = newarr.slice((page - 1) * count, page * count)
    // 查询到的信息的总页数
    let total = Math.ceil(newarr.length / count)
    res.send({ code: 200, msg: '查询完毕', list: searcharr, total: total })
})
// 删除功能
userRouter.post('/delete', (req, res) => {
    let { phone } = req.body
    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let i = arr.findIndex((item) => {
        return item.phone == phone
    })
    arr.splice(i, 1)
    fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8')
    res.send({ code: 200, msg: '删除成功' })
})

module.exports = userRouter